<template>
  <div class="common">
    <!-- 固定头部 -->
    <div class="fixed-header">
      <div class="common-title">
        美食社区
        <div class="add" @click="() => router.push({ path: '/editCook' })">+</div>
      </div>
      <van-search v-model="searchValue" placeholder="搜索食谱" />
    </div>

    <!-- 可滚动内容区域 -->
    <div class="scroll-content">
      <commonItem :currentData="filteredData"></commonItem>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';
import router from '@/router/index.js';
import { getCommonCook } from '@/api/index.js';
import commonItem from '@/components/commonItem.vue'

const searchValue = ref('') // 用户在搜索框中的输入
const allData = ref([]) // 所有菜的数据
const currentData = ref([]) // 当前展示的数据

// 计算属性来动态生成过滤后的数据
const filteredData = computed(() => {
  if (!searchValue.value) {
    return currentData.value; // 如果没有搜索词，返回所有数据
  }
  // 根据搜索词过滤数据
  return currentData.value.filter(item =>
    item.name && item.name.toLowerCase().includes(searchValue.value.toLowerCase())
  );
});

onMounted(async () => {
  const res = await getCommonCook()
  currentData.value = res.data
})
</script>

<style lang="less" scoped>
.common {
  height: 100vh;
  display: flex;
  flex-direction: column;

  .fixed-header {
    position: sticky;
    top: 0;
    z-index: 999;
    background-color: #fff;

    .common-title {
      padding: 0 16px;
      height: 56px;
      font-size: 18px;
      line-height: 56px;
      font-weight: 500;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .add {
        text-align: center;
        color: #FFF;
        width: 40px;
        height: 40px;
        line-height: 40px;
        background-color: #FF6B6B;
        border-radius: 6px;
      }
    }

    .van-search {
      padding: 8px 16px;
    }
  }

  .scroll-content {
    flex: 1;
    overflow-y: auto;
    padding-bottom: 55px; // 底部留白，防止被 tabbar 遮挡（如果有的话）
  }
}
</style>